package com.example.day4_week1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private MyAdapter myAdapter;
    private List<FoodEntity.DataBean> list;

    int item_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.lv);
        list = new ArrayList<>();
        myAdapter = new MyAdapter(list,this);
        listView.setAdapter(myAdapter);
        //为listview绑定上下文菜单
        registerForContextMenu(listView);
        new MyTask().execute("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=邓紫棋&type=1&offset=40&total=true&limit=20");
    }
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        //获取对应的item的positon
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        item_id = info.position;//选择的listview的当前id
        switch (item.getItemId()){
            case R.id.delete:
                //删除
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification.Builder builder = new Notification.Builder(this);
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setContentTitle(list.get(item_id).getFood_str()+"");
                builder.setContentText(list.get(item_id).getTitle()+"");
                Intent intent = new Intent(this,MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 101, intent, PendingIntent.FLAG_ONE_SHOT);
                builder.setContentIntent(pendingIntent);
                notificationManager.notify(1,builder.build());
                list.remove(item_id);
                myAdapter.notifyDataSetChanged();
                break;
            case R.id.sort:
                //排序
                Collections.sort(list, new Comparator<FoodEntity.DataBean>() {
                    @Override
                    public int compare(FoodEntity.DataBean o1, FoodEntity.DataBean o2) {
                        return o1.getNum() - o2.getNum();
                    }
                });
                myAdapter.notifyDataSetChanged();

                break;
        }
        return super.onContextItemSelected(item);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.menu,menu);
    }

    //点击返回键 退出
    long lastTime = 0;//必须声明成员变量
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){//点击返回键
            if(System.currentTimeMillis() - lastTime >1000){//单击
                Toast.makeText(this, "再按一次退出app", Toast.LENGTH_SHORT).show();
                lastTime = System.currentTimeMillis();//记录这次的时间
                return false;//不关闭activity
            }else{//双击
                lastTime = System.currentTimeMillis();//记录这次的时间
                finish();

            }
        }
        return super.onKeyDown(keyCode, event);
    }



    class MyTask extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url=new URL(strings[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setConnectTimeout(1000);
                httpURLConnection.setReadTimeout(1000);
                httpURLConnection.connect();
                if(httpURLConnection.getResponseCode()==200){
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String a="";
                    StringBuffer stringBuffer=new StringBuffer();
                    while((a=bufferedReader.readLine())!=null){
                        stringBuffer.append(a);
                    }
                    String string = stringBuffer.toString();
                    return string;
                }
            } catch (MalformedURLException e) {


            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.d("ytx", "onPostExecute: "+s);
//            //
//            JSONObject jsonObject = null;
//            try {
//                jsonObject = new JSONObject(s);
//                JSONArray data = jsonObject.getJSONArray("data");
//                for (int i = 0; i < data.length(); i++) {
//                    JSONObject jsonObject1 = data.getJSONObject(i);
//                    String title = jsonObject1.getString("title");
//                    String pic = jsonObject1.getString("pic");
//                    int num = jsonObject1.getInt("num");
//                    FoodEntity.DataBean dataBean = new FoodEntity.DataBean();
//                    dataBean.setPic(pic);
//                    dataBean.setTitle(title);
//                    dataBean.setNum(num);
//                    list.add(dataBean);
//                }
//                myAdapter.notifyDataSetChanged();
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }



        }
    }


}
